package com.da.lon.wang.xlg.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.GridView;
import android.widget.ListAdapter;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class XLGDataUtils {

    public final static float DENSITY = Resources.getSystem()
            .getDisplayMetrics().density;

    public static float getRatingBarValue(float value) {
        float f = 0.5f;
        int i = (int) value;
        float v = value - i;
        if (v >= 0.5 && v <= 0.9) {
            f = i + 1;
        } else {
            f = (float) (i + 0.5);
        }
        return f;

    }

    /**
     * md5加密
     */
    public static String encrypt2MD5(String string) {

        byte[] hash;

        try {

            hash = MessageDigest.getInstance("MD5").digest(
                    string.getBytes("UTF-8"));

        } catch (NoSuchAlgorithmException e) {

            throw new RuntimeException("Huh, MD5 should be supported?", e);

        } catch (UnsupportedEncodingException e) {

            throw new RuntimeException("Huh, UTF-8 should be supported?", e);

        }

        StringBuilder hex = new StringBuilder(hash.length * 2);

        for (byte b : hash) {

            if ((b & 0xFF) < 0x10)
                hex.append("0");

            hex.append(Integer.toHexString(b & 0xFF));

        }

        return hex.toString();

    }

    public static int dipToPixel(int dip) {
        return (int) (dip * DENSITY + 0.5f);
    }

    public static float pixelToDip(float px) {
        return (px - 0.5f) / DENSITY;
    }

    /**
     * float保留小数
     *
     * @param num - 保留的位数
     */

    public static float getFloatValue(float value, int num) {
        BigDecimal b = new BigDecimal(value);
        float f = b.setScale(num, BigDecimal.ROUND_HALF_UP).floatValue();
        return f;
    }

    /**
     * 获取价格两位小数float
     */

    public static float getPriceFloat(String value) {
        float f = 0.0f;
        try {
            BigDecimal b = new BigDecimal(Float.parseFloat(value));
            f = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        } catch (Exception e) {
            return f;
        }
        return f;
    }

    /**
     * 获取价格两位小数String
     */

    public static String getPriceString(String value) {

        String f = "0.0";
        try {
            BigDecimal b = new BigDecimal(Float.parseFloat(value));
            f = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue() + "";
            if (f.length() - f.indexOf(".") == 2) {
                f += "0";
            }
        } catch (Exception e) {
            return value;
        }
        return f;
    }

    /**
     * 判断手机格式是否正确
     */
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern
                .compile("^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);

        return m.matches();
    }

    /**
     * 判断身份证号格式是否正确
     */
    public static boolean isIdentityCard(String identityCardNum) {
        //定义判别用户身份证号的正则表达式（要么是15位，要么是18位，最后一位可以为字母）  
        Pattern idNumPattern = Pattern.compile("(\\d{14}[0-9a-zA-Z])|(\\d{17}[0-9a-zA-Z])");
        //通过Pattern获得Matcher  
        Matcher idNumMatcher = idNumPattern.matcher(identityCardNum);

        return idNumMatcher.matches();
    }

    /**
     * 获取Get的URL参数
     */
    public static String getUrlParam(String des, String key) {
        String[] contents = des.split("&");
        for (int i = 0; i < contents.length; i++) {
            if (contents[i].contains(key)) {
                return contents[i].substring(key.length() + 1);
            }
        }
        return "";
    }

    /**
     * 是否安某个应用
     */

    public static boolean isInstallApp(Context context, String packageName) {
        boolean isInstall = false;

        try {
            final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
            List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
            List<String> pName = new ArrayList<String>();// 用于存储所有已安装程序的包名
            // 从pinfo中将包名字逐一取出，压入pName list中
            if (pinfo != null) {
                for (int i = 0; i < pinfo.size(); i++) {
                    String pn = pinfo.get(i).packageName;
                    pName.add(pn);
                }
            }
            isInstall = pName.contains(packageName);// 判断pName中是否有目标程序的包名，有TRUE，没有FALSE
        } catch (Exception e) {
            e.printStackTrace();
        }

        return isInstall;
    }

    /* 时间戳转换成字符窜 */
    public static String getDateToString(String timestampString, String formats) {
        Long timestamp = Long.parseLong(timestampString) * 1000;
        String date = new java.text.SimpleDateFormat(formats)
                .format(new java.util.Date(timestamp));
        return date;
    }


    /**
     * 动态获取gridView的总高度
     *
     * @param listView girdView对象
     * @param type2    =0 传全部
     */
    public static void setListViewHeightBasedOnChildren(GridView listView, int type2) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int col = 2;// listView.getNumColumns();
        int totalHeight = 0;
        int countLength = 0;
        // i每次加4，相当于listAdapter.getCount()小于等于4时 循环一次，计算一次item的高度，
        // listAdapter.getCount()小于等于8时计算两次高度相加
        if (type2 == 1) {
            if (listAdapter.getCount() < 6) {
                countLength = listAdapter.getCount();
            } else {
                countLength = 6;
            }
        } else if (type2 == 0) {
            countLength = listAdapter.getCount();
        }
        for (int i = 0; i < countLength; i += col) {
            // 获取listview的每一个item
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredHeight();
        }

        // 获取listview的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
        // 设置margin
        ((MarginLayoutParams) params).setMargins(7, 7, 7, 7);
        // 设置参数
        listView.setLayoutParams(params);
    }

}
